import { useState, useEffect, useRef } from "react";
import { FriendRequest, FriendRequestStatus } from "@/types/friend-request";
import {
  getFriendApplyListApi,
  acceptFriendApplyApi,
  rejectFriendApplyApi,
} from "@/services/api/friend-request";
import { ResponseCode } from "@/types/api-common";
import { AlertRefType } from "@/components/Global/Alert/types";

interface UseFriendRequestsProps {
  alertRef: React.RefObject<AlertRefType>;
}

interface UseFriendRequestsReturn {
  requests: FriendRequest[];
  loading: boolean;
  refreshing: boolean;
  error: string | null;
  fetchRequests: () => Promise<void>;
  handleRefresh: () => void;
  handleAccept: (id: string) => Promise<void>;
  handleReject: (id: string) => Promise<void>;
}

export const useFriendRequests = ({
  alertRef,
}: UseFriendRequestsProps): UseFriendRequestsReturn => {
  const [requests, setRequests] = useState<FriendRequest[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // 获取申请列表
  const fetchRequests = async () => {
    try {
      setLoading(true);
      setError(null);
      const response = await getFriendApplyListApi();

      if (response.data.code === ResponseCode.SUCCESS) {
        setRequests(response.data.data || []);
      } else {
        setError("获取申请列表失败");
      }
    } catch (err) {
      setError("网络错误，请稍后重试");
      console.error("获取好友申请列表出错:", err);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  // 处理下拉刷新
  const handleRefresh = () => {
    setRefreshing(true);
    fetchRequests();
  };

  // 处理接受申请
  const handleAccept = async (id: string) => {
    try {
      const response = await acceptFriendApplyApi(id);

      if (response.data.code === ResponseCode.SUCCESS) {
        // 更新本地状态
        setRequests((prevRequests) =>
          prevRequests.map((request) =>
            request.id === id
              ? { ...request, status: FriendRequestStatus.ACCEPTED }
              : request
          )
        );
        alertRef.current?.show("success", "已接受好友申请");
      } else {
        alertRef.current?.show("error", "操作失败，请重试");
      }
    } catch (err) {
      alertRef.current?.show("error", "网络错误，请稍后重试");
      console.error("接受好友申请出错:", err);
    }
  };

  // 处理拒绝申请
  const handleReject = async (id: string) => {
    try {
      const response = await rejectFriendApplyApi(id);

      if (response.data.code === ResponseCode.SUCCESS) {
        // 更新本地状态
        setRequests((prevRequests) =>
          prevRequests.map((request) =>
            request.id === id
              ? { ...request, status: FriendRequestStatus.REJECTED }
              : request
          )
        );
        alertRef.current?.show("success", "已拒绝好友申请");
      } else {
        alertRef.current?.show("error", "操作失败，请重试");
      }
    } catch (err) {
      alertRef.current?.show("error", "网络错误，请稍后重试");
      console.error("拒绝好友申请出错:", err);
    }
  };

  useEffect(() => {
    fetchRequests();
  }, []);

  return {
    requests,
    loading,
    refreshing,
    error,
    fetchRequests,
    handleRefresh,
    handleAccept,
    handleReject,
  };
};
